// oss
import oss from 'ali-oss';
import moment from 'moment';

class OSSUploader {
  constructor () {

  }

  getUploadPath = (file) => {
    // 上传文件的路径，使用日期命名文件目录
    return `${moment().format('YYYYMMDD')}/${file.name.split(".")[0]}-${file.uid}.${file.type.split("/")[1]}`;
  }

  ossUpload = (url, file) => {
    return new Promise((resolve, reject) => {
      this
      .client
      .multipartUpload(url, file)
      .then(data => {
        resolve(data);
      }).catch(error => {
        reject(error)
      })
    })
  }

  /// public methods

  config (params) {
    this.client = new oss(params);
  }

  do (file, callback) {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      return { err: -400, msg: '只能上传 JPG/PNG 文件!' };
    }
    const isLimit4M = file.size / 1024 / 1024 < 4;
    if (!isLimit4M) {
      return { err: -401, msg: '图片不能超过 4MB!' };
    }

    const url = this.getUploadPath(file);
    const that = this;
    const reader = new FileReader();
    // reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(file);
    reader.onloadend = () => {
      that.ossUpload(url, file).then(data => {
        // callback
        // http://wizarpos-mall.oss-cn-shanghai.aliyuncs.com/20200102/1-rc-upload-1577899708333-8.png?uploadId=1416F9FD5DE24DBF85F958070F50C989 
        const url = data.res.requestUrls[0];
        const urlStrings = url.split('?');
        callback(urlStrings[0]);
      })
    }

    return { res: false, msg: '成功' };
  }

  toParse (img, callback) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  }
}

export default new OSSUploader();